package com.alex.mylibrary.utils;

import android.os.Build;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created by
 * Author: alex
 * Email:
 * Date: 15-10-12.
 */
public final class HttpTools {

    private HttpTools(){

    }

    private static final int CONNECT_TIMEOUT = 5000;

    private static final int READ_TIMEOUT = 10000;

    public static final String USER_AGENT = "ting_4.1.7("+ Build.MODEL+","+Build.VERSION.SDK_INT +")";

    public static byte[] doGet(String url){
        byte[] ret = null;

        if (url != null) {

            HttpURLConnection connection = null;
            InputStream inputStream = null;
            ByteArrayOutputStream byteArrayOutputStream = null;

            try {
                URL u = new URL(url);
                connection = (HttpURLConnection) u.openConnection();

                // 设置连接的配置
                connection.setConnectTimeout(CONNECT_TIMEOUT);
                connection.setReadTimeout(READ_TIMEOUT);

                connection.setRequestMethod("GET");

                // 完善 Http 请求的内容
                // 1. 设定通用的 Http 头信息
//                connection.setRequestProperty("Accept","application/*,text/*,image/*,*/*");
                // 设置接受的内容压缩编码算法
                connection.setRequestProperty("Accept-Encoding","gzip");
                // 设置 User-Agent
                connection.setRequestProperty("User-Agent",USER_AGENT);

                connection.connect();
                int code = connection.getResponseCode();


                if (code == 200){
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    inputStream = connection.getInputStream();

                    //支持解压缩
                    String encoding = connection.getContentEncoding();
                    if ("gzip".equals(encoding)){
                        inputStream = new GZIPInputStream(inputStream);
                    }

                    //另一种方式
//                    String headerField = connection.getHeaderField("Content-Encoding");
//                    if ("gzip".equals(headerField)){
//                        inputStream = new GZIPInputStream(inputStream);
//                    }

                    ret = StreamUtil.readStream(inputStream);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return ret;
    }

}
